package com.yunkaweilai.android.activity.operation.recharge;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.PopupShopEmployee;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.model.operation.CreateSelectedGoodsModel;
import com.yunkaweilai.android.model.shop.ShopSkuInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.popup.JiciValidityPopup;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 计次商品确认界面
 * Created by Administrator on 2017/7/20.
 */

public class ConfirmJiciListActivity extends BaseActivity implements PopupShopEmployee {

    @BindView(R.id.id_listview)
    ListView idListview;
    @BindView(R.id.id_tv_all_price)
    TextView idTvAllPrice;
    @BindView(R.id.id_tv_guadan)
    TextView idTvGuadan;
    @BindView(R.id.id_tv_checkout)
    TextView idTvCheckout;
    @BindView(R.id.content_view)
    LinearLayout contentView;
    @BindView(R.id.id_multipleStatusView)
    MultipleStatusView idMultipleStatusView;
    private String goodsStr = "";
    private CreateSelectedGoodsModel createSelectedGoodsModel;//订单数据
    private CommonAdapter<CreateSelectedGoodsModel.DataBean.GoodsListBean> adapter;
    private ArrayList<CreateSelectedGoodsModel.DataBean.GoodsListBean> list = new ArrayList<>();
    private Map<String, ShopSkuInfoModel> selectedMaps = BaseApplication.getSelectedMaps();
    public static final String JICI_CONFIRM_RECHARGE_MODEL = "JICI_CONFIRM_RECHARGE_MODEL";
    public static final String JICI_CONFIRM_RECHARGE_BUNDLE = "JICI_CONFIRM_RECHARGE_BUNDLE";
    private MemberHeadModel model;
    public static void actionStart(Context context, MemberHeadModel model){
        Intent intent = new Intent(context,ConfirmJiciListActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(JICI_CONFIRM_RECHARGE_MODEL,model);
        intent.putExtra(JICI_CONFIRM_RECHARGE_BUNDLE,bundle);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_shop_list);
        ButterKnife.bind(this);
        idTvGuadan.setVisibility(View.GONE);
        idMultipleStatusView.showLoading();
        idMultipleStatusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initHttp(false);
            }
        });
        new TitleBuilder(mAc).setTitleText("确认商品")
                .setLeftImage(R.mipmap.ic_go_back)
                .setLeftOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        model = (MemberHeadModel) getIntent().getBundleExtra(JICI_CONFIRM_RECHARGE_BUNDLE).getSerializable(JICI_CONFIRM_RECHARGE_MODEL);
        createStr();
        initAdapter();
        initHttp(false);
        initClick();
    }

    private void initClick() {
        idTvCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedMaps.size() > 0){
                    String selectedGoodsStr = createSelectedGoodsModel.getData().getOrderInfo().getSelectedGoodsStr();
                    String payment = createSelectedGoodsModel.getData().getOrderInfo().getPayment();
                    BaseApplication.jiciGoodsList = list;
                    RechargeReceivablesActivity.actionStart(mAc, payment + "", selectedGoodsStr,model,createSelectedGoodsModel.getData().getOrderInfo().getZ_goods_discount_price());
                }else{
                    showToast("还未选择商品");
                }

            }
        });


    }

    private void initAdapter() {
        adapter = new CommonAdapter<CreateSelectedGoodsModel.DataBean.GoodsListBean>(mAc, R.layout.item_list_recharge_shop, list) {
            @Override
            protected void convert(ViewHolder viewHolder, final CreateSelectedGoodsModel.DataBean.GoodsListBean item, final int position) {
                ImageView mIdImg = viewHolder.getView(R.id.id_img);
                Utils.shopInfoImg(mAc,item.getGoods_image(),mIdImg);
                viewHolder.setText(R.id.id_tv_name, item.getGoods_name() + "");
                TextView price2 = viewHolder.getView(R.id.id_tv_price2);
                price2.setText(item.getShop_price()+"");
                viewHolder.setText(R.id.id_tv_price, Utils.ManageMoney(item.getShop_discount_price()) + "");
                price2.setVisibility(View.VISIBLE);
                price2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);

                viewHolder.setText(R.id.id_tv_unit, "/" + item.getUnit());
                ImageView idImgAdd = viewHolder.getView(R.id.id_img_add);
                ImageView idImgDel = viewHolder.getView(R.id.id_img_del);
                TextView idTvAddNum = viewHolder.getView(R.id.id_tv_add_num);
                if (Double.parseDouble(item.getGoods_num()) > 0) {
                    idImgDel.setVisibility(View.VISIBLE);
                    idTvAddNum.setText(item.getGoods_num() + "");
                    idTvAddNum.setVisibility(View.VISIBLE);
                } else {
                    idImgDel.setVisibility(View.GONE);
                    idTvAddNum.setText("0");
                    idTvAddNum.setVisibility(View.GONE);
                }

                TextView idTvCommission = viewHolder.getView(R.id.id_tv_commission);
                idTvCommission.setVisibility(View.VISIBLE);
                if (StringUtils.isEmpty(item.getValidityStr())){
                    idTvCommission.setText("设置有效期");
                    item.setValidityStr("永久有效");
                }else{
                    idTvCommission.setText(item.getValidityStr());
                }

                //设置有效期
                idTvCommission.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        JiciValidityPopup jiciValidityPopup = new JiciValidityPopup(mAc, item.getGoods_id(),item.getGoods_type(),item);
                        jiciValidityPopup.setInterface(ConfirmJiciListActivity.this);
                        jiciValidityPopup.showPopupWindow();
                    }
                });


                //增加
                idImgAdd.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(item.getGoods_sku());

                        item.setGoods_num((Double.parseDouble(item.getGoods_num()) + 1)+"");
                        if (shopSkuInfoModel == null) {
                            shopSkuInfoModel = createSkuModel(item.getGoods_image(), item.getGoods_num(), item.getGoods_id(), item.getGoods_sku()
                                    , item.getGoods_name(), item.getShop_price() + "", item.getGoods_category_parent_id());
                            selectedMaps.put(item.getGoods_sku(), shopSkuInfoModel);
                        } else {
                            shopSkuInfoModel.setBuy_num(Double.parseDouble(item.getGoods_num()));
                        }
                        refreshShopCart();

                    }
                });


                //减少
                idImgDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(item.getGoods_sku());
                        double nums = Double.parseDouble(item.getGoods_num()) - 1;
                        item.setGoods_num(nums <= 0 ? "0" : nums+"");
                        if (shopSkuInfoModel == null) {
                            if (Double.parseDouble(item.getGoods_num()) > 0) {
                                shopSkuInfoModel = createSkuModel(item.getGoods_image(),item.getGoods_num(),item.getGoods_id()
                                        ,item.getGoods_sku(),item.getGoods_name(),item.getShop_price() + "",item.getGoods_category_parent_id());
                                selectedMaps.put(item.getGoods_sku(),shopSkuInfoModel);
                            }
                        } else {
                            if (Double.parseDouble(item.getGoods_num()) > 0) {
                                shopSkuInfoModel.setBuy_num(Double.parseDouble(item.getGoods_num()));
                            } else {
                                selectedMaps.remove(shopSkuInfoModel.getSku());
                                BaseApplication.selectedMaps = selectedMaps;
                                list.remove(position);
                            }
                        }
                        refreshShopCart();
                    }
                });

            }
        };

        idListview.setAdapter(adapter);
    }

    private void refreshShopCart() {
        showProgressDialog("正在修改商品!");
        createStr();
        initHttp(true);
    }


    //创建商品model，用于全局记录
    private ShopSkuInfoModel createSkuModel(String url, String buy_num, String id, String sku, String good_name, String shop_price, String goods_category_parent_id) {
        ShopSkuInfoModel shopSkuInfoModel = new ShopSkuInfoModel();
        shopSkuInfoModel.setBuy_num(Double.parseDouble(buy_num));
        shopSkuInfoModel.setSku_id(id);
        shopSkuInfoModel.setSku(sku);
        shopSkuInfoModel.setSku_name(good_name);
        shopSkuInfoModel.setAdvUrl(url);
        shopSkuInfoModel.setGoods_type("Jici");
        shopSkuInfoModel.setShop_price(Float.parseFloat(shop_price));
        shopSkuInfoModel.setGoods_category_parent_id(goods_category_parent_id);
        shopSkuInfoModel.setSpec_str_md5("");
        shopSkuInfoModel.setMay_use_stock(9999);
        return shopSkuInfoModel;
    }

    //底部订单数据
    private void initOrderView() {
        String prices = Utils.ManageMoney(createSelectedGoodsModel.getData().getOrderInfo().getZ_discount_price());
        idTvAllPrice.setText(prices);
    }

    //生成商品字符串
    private void createStr() {
        goodsStr = "";
        for (String key : selectedMaps.keySet()) {
            ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(key);
            goodsStr = goodsStr + shopSkuInfoModel.getSku_id() + "|" + shopSkuInfoModel.getBuy_num() + "|" + shopSkuInfoModel.getGoods_type() +
                    "|,";
        }
        if (goodsStr.length() > 0){
            goodsStr = goodsStr.substring(0, goodsStr.length() - 1);
        }
    }

    private void initHttp(final boolean flag) {
        HttpRequest.postUrl(Api.CREATE_SELECTED_JICI_RECHARGE)
                .addParams("SelectedGoodsStr", goodsStr)
                .addParams("member_id",model.getId())
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            createSelectedGoodsModel = gson.fromJson(json, CreateSelectedGoodsModel.class);
                            list.clear();
                            list.addAll(createSelectedGoodsModel.getData().getGoodsList());

                            Map<String, ShopSkuInfoModel> otherMap = new HashMap<>();
                            for (int i = 0; i < createSelectedGoodsModel.getData().getGoodsList().size(); i++) {
                                CreateSelectedGoodsModel.DataBean.GoodsListBean goodsListBean = createSelectedGoodsModel.getData().getGoodsList().get(i);
                                ShopSkuInfoModel shopSkuInfoModel = selectedMaps.get(goodsListBean.getGoods_sku());
                                if (shopSkuInfoModel != null) {
                                    otherMap.put(goodsListBean.getGoods_sku(), shopSkuInfoModel);
                                }
                            }
                            BaseApplication.selectedMaps = otherMap;
                            initOrderView();

                            adapter.notifyDataSetChanged();
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showContent();
                            }
                            if (flag){
                                dismissProgressDialog();
                                EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.SHOP_CART_INFO_REFRESH, true));
                            }
                        } else {
                            if (idMultipleStatusView != null) {
                                idMultipleStatusView.showError();
                            }
                            if (flag){
                                dismissProgressDialog();
                            }
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (idMultipleStatusView != null) {
                            idMultipleStatusView.showError();
                        }
                        if (flag){
                            dismissProgressDialog();
                        }
                    }
                });
    }

    @Override
    public void refresh() {
        adapter.notifyDataSetChanged();
    }
}
